import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Form,
  Modal,
  Card,
  Input,
  Select,
  Space,
  Button,
  message,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { history, connect } from 'umi';
import type { ConnectProps } from 'umi';
import trans from '@/utils/translate';
import { addDevice, getDevice, updateDevice } from './service';
import { device } from '.';
import { nameRule } from '@/utils/rule';

const { Item } = Form;
const { Option } = Select;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 12 },
};
interface Props extends ConnectProps {
  currentUser: any;
}
const Add: React.FC<Props> = (props) => {
  console.log(props);
  const [form] = Form.useForm();
  const { currentUser, match } = props;
  const { id } = match?.params as { id: number };
  const handleSubmit = (e: device) => {
    const params = e.creator ? e : { ...e, creator: currentUser.username, id: Number(id) };
    (id ? updateDevice : addDevice)(params).then(res => {
      if (res && res.code === 0) {
        message.success(trans(`operation.${id ? 'update' : 'create'}.success`));
        history.push('/node-management/terminal-device');
      }
    })
  }

  useEffect(() => {
    // 如果路由有 ID，则是编辑，否则是创建
    if (id) {
      getDevice(id).then(res => {
        if (res && res.code === 0) {
          console.log(res.data.camera);
          const {
            name,
            proto,
            ip,
            port,
            user,
            passwd,
            creator,
            desc,
          } = res.data.camera;
          form.setFieldsValue({
            name,
            proto,
            ip,
            port,
            user,
            passwd,
            creator,
            desc,
          });
        }
      })
    }
  }, [])

  return (
    <PageContainer
      onBack={() => {
        Modal.confirm({
          centered: true,
          closable: true,
          icon: <ExclamationCircleOutlined />,
          maskClosable: true,
          okType: 'danger',
          okText: trans('operation.confirm'),
          cancelText: trans('operation.cancel'),
          width: '30%',
          title: <div style={{ fontWeight: 'bold' }}>{trans('operation.exit.confirm')}</div>,
          content: <div>{trans('operation.exit.content')}</div>,
          onOk: async () => {
            history.push('/node-management/terminal-device')
          },
          cancelButtonProps: {},
          onCancel: () => {},
        });
      }}
    >
      <Card>
        <Form
          { ...layout }
          form={form}
          onFinish={handleSubmit}
        >
          <Item
            label={trans('device.name')}
            required
            name='name'
            rules={nameRule()}
          >
            <Input></Input>
          </Item>
          <Item label={trans('info.description')} name="desc">
            <Input.TextArea maxLength={200} showCount placeholder='请输入描述，限制 200 字符以内' />
          </Item>
          <Item
            label={trans('device.type')}
            required
            name='type'
            initialValue='摄像头'
          >
            <Select>
              <Option value='摄像头'>摄像头</Option>
            </Select>
          </Item>
          <Item
            label={trans('device.ip')}
            required
            name='ip'
          >
            <Input placeholder={trans('device.ip.please')}></Input>
          </Item>
          <Item
            label={trans('device.protocol')}
            required
            name='proto'
            initialValue='ONVIF'
          >
            <Select>
              <Option value='ONVIF'>ONVIF</Option>
            </Select>
          </Item>
          <Item
            label={trans('device.port')}
            required
            name='port'
            initialValue={2000}
          >
            <Input readOnly></Input>
          </Item>
          <Item
            label={trans('info.userName')}
            required
            name='user'
          >
            <Space>
              <Input></Input>
              <span>{trans('device.userName.tip')}</span>
            </Space>

          </Item>
          <Item
            label={trans('info.password')}
            required
            name='passwd'
          >
            <Space>
              <Input.Password></Input.Password>
              <span>{trans('device.password.tip')}</span>
            </Space>
          </Item>
          <Item wrapperCol={{offset: '4'}}>
            <Button type='primary' htmlType='submit'>{trans('operation.confirm')}</Button>
            <Button
              style={{marginLeft: '5px'}}
              onClick={() => history.push('/node-management/terminal-device')}
            >{trans('operation.cancel')}</Button>
          </Item>
        </Form>
      </Card>
    </PageContainer>
  )
}

export default connect(({ user }: any) => ({
  currentUser: user.currentUser,
}))(Add);
